package cc.mrbird.febs.customer.controller;


import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.customer.entity.Activity;
import cc.mrbird.febs.customer.entity.Order;
import cc.mrbird.febs.customer.entity.Share;
import cc.mrbird.febs.customer.service.IActivityService;
import cc.mrbird.febs.customer.service.IOrderService;
import cc.mrbird.febs.customer.service.IShareService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 活动详情表 前端控制器
 * </p>
 *
 * @author Macw
 * @since 2020-11-02
 */
@RestController
@RequestMapping("/activity")
public class ActivityController extends BaseController {

    @Resource
    private IActivityService activityService;
    
    @Resource
    private IShareService shareService;

    @Resource
    private IOrderService orderService;


    /**
     * 查询活动列表方法
     * @param activity
     * @param queryRequest
     * @return
     */
    @RequestMapping("getActivityList")
    @ControllerEndpoint(operation = "查询活动", exceptionMessage = "查询活动失败")
    public FebsResponse getActivityList(Activity activity, QueryRequest queryRequest){
        Page<Activity> page = new Page<>(queryRequest.getPageNum(), queryRequest.getPageSize());

        IPage<Activity> page1 = activityService.page(page, new QueryWrapper<Activity>().lambda()
                .like(StringUtils.isNotBlank(activity.getName()), Activity::getName, activity.getName())
                .like(StringUtils.isNotBlank(activity.getPosition()), Activity::getPosition, activity.getPosition())
                .orderByDesc(Activity::getCreateTime));
        return new FebsResponse().success().data(getDataTable(page1));
    }

    /**
     * 富文本编辑器上传文件方法
     * @param file
     * @return
     */
    @RequestMapping("/uploadActivityPic")
    public Map<String,Object> productPicUrl(MultipartFile file) {
        String basePath = "activityPic";
        String url = null;
        Map<String,Object> map = new HashMap<>();
        url = aliOSSUpload(file, basePath);
        map.put("errno", 0);
        List<String> list = new ArrayList<>();
        list.add(url);
        map.put("data", list);
        return map;
    }

    @PostMapping("/addOrUpdate")
    @RequiresPermissions("activity:update")
    @ControllerEndpoint(operation = "新增/修改活动", exceptionMessage = "新增/修改活动失败")
    public FebsResponse addOrUpdateActivity(@Valid Activity activity, @RequestParam("headPhoto_file") MultipartFile headPhoto_file, @RequestParam("wechat_file") MultipartFile wechat_file, @RequestParam("videoUrl_file") MultipartFile videoUrl_file) {
        try{
            if (StringUtils.isBlank(activity.getTActivityId())){
                if (headPhoto_file.getSize() <=0 || wechat_file.getSize()<=0 || videoUrl_file.getSize()<=0){
                    return new FebsResponse().fail().message("图片或者音频不能为空");
                }
            }
            if (getHeadPhoto(activity, headPhoto_file, wechat_file, videoUrl_file))
                return new FebsResponse().fail().message("音频上传失败");
            if (StringUtils.isBlank(activity.getTActivityId())){
                activity.setCreateTime(LocalDateTime.now());
                activity.setTActivityId(FebsUtil.getUUID6());
                activityService.save(activity);
                Share share = new Share();
                share.setImgUrl(activity.getHeadPhoto());
                share  = activity.getIsPublish() == 1 ? share.setStatus(1) : share.setStatus(0);
                share.setTitle(activity.getName());
                share.setActivityId(activity.getTActivityId());
                share.setCreateTime(LocalDateTime.now());
                shareService.save(share);
                String url = "http://chanwu.macw.cc/"+"?activityId="+activity.getTActivityId();
                share.setShareUrl(url);
                shareService.updateById(share);
            }else{
                activityService.updateById(activity);
            }
            return new FebsResponse().success();
        }catch(Exception e){
            return new FebsResponse().fail();
        }
    }

    private boolean getHeadPhoto(@Valid Activity activity, @RequestParam("headPhoto_file") MultipartFile headPhoto_file, @RequestParam("wechat_file") MultipartFile wechat_file, @RequestParam("videoUrl_file") MultipartFile videoUrl_file) {
        if (headPhoto_file != null && headPhoto_file.getSize() > 0) {
            //获取上传文件的路径
            String url = uploadArticle(headPhoto_file);
            //将文件大小，和文件上传后返回的路径，入库
            activity.setHeadPhoto(url);
        }
        if(wechat_file != null && wechat_file.getSize() > 0){
            String url = uploadArticle(wechat_file);
            activity.setServicePhoto(url);
        }

        if (videoUrl_file != null && videoUrl_file.getSize() > 0) {
            //获取上传文件的路径
            try{
                String url = uploadArticle(videoUrl_file);
                activity.setVideoUrl(url);
            }catch(Exception e){
                return true;
            }

        }
        return false;
    }

    @PostMapping("/updateActivity")
    @RequiresPermissions("activity:update")
    @ControllerEndpoint(operation = "修改活动", exceptionMessage = "修改活动失败")
    public FebsResponse updateActivity(@Valid Activity activity, @RequestParam("headPhoto_file") MultipartFile headPhoto_file, @RequestParam("wechat_file") MultipartFile wechat_file, @RequestParam("videoUrl_file") MultipartFile videoUrl_file) {
        try{
            if (getHeadPhoto(activity, headPhoto_file, wechat_file, videoUrl_file))
                return new FebsResponse().fail().message("音频上传失败");
            activityService.updateById(activity);
            return new FebsResponse().success();
        }catch(Exception e){
            return new FebsResponse().fail();
        }
    }


    @PostMapping("updateContent")
    @RequiresPermissions("activity:update")
    @ControllerEndpoint(operation = "修改活动内容", exceptionMessage = "修改活动内容")
    public FebsResponse updateContent(Activity activity){
        try{
            activityService.updateById(activity);
        }catch(Exception e){
            return new FebsResponse().fail();
        }
        return new FebsResponse().success();
    }

    @PostMapping("updatePublish")
    @RequiresPermissions("activity:update")
    @ControllerEndpoint(operation = "发布活动", exceptionMessage = "发布活动失败")
    public FebsResponse updatePublish(Activity activity){
        try{
            activityService.updateById(activity);
            QueryWrapper<Share> wrapper = new QueryWrapper<>();
            wrapper.eq("activity_id",activity.getTActivityId());
            Share one = shareService.getOne(wrapper);
            if(activity.getIsPublish()==1){
                one.setStatus(1);
                String url = "http://chanwu.macw.cc/"+"?activityId="+activity.getTActivityId();
                one.setShareUrl(url);
                shareService.updateById(one);
            }else{
                one.setStatus(0);
                shareService.updateById(one);
            }
        }catch(Exception e){
            return new FebsResponse().fail();
        }
        return new FebsResponse().success();
    }


    public static String convertArrayToString(String[] strArr) {
        if (strArr == null || strArr.length == 0) {
            return "";
        }
        String res = "";
        for (int i = 0, len = strArr.length; i < len; i++) {
            if (",".equals(strArr[i])){
                continue;
            }else{
                res += strArr[i];
                if (i < len - 1) {
                    res += "";
                }
            }
        }
        return res;
    }


    /**
     * 封装上传方法
     * @param file
     * @return
     */
    public String uploadArticle(MultipartFile file){
        String basePath = "activity";
        String url = "";
        url =  aliOSSUpload(file, basePath);
        return url;
    }

    /**
     * 获取活动内容接口
     * @param tActivityId
     * @return
     */
    @GetMapping("/getContent")
    public FebsResponse getContent(String tActivityId){
        Activity activity = activityService.getOne(new QueryWrapper<Activity>().lambda()
                .eq(Activity::getTActivityId, tActivityId)
                .select(Activity::getContent));
        return new FebsResponse().success().data(activity.getContent());
    }

    /**
     * 删除和批量删除
     * @param tActivityIds
     * @return
     */
    @GetMapping("delete/{tActivityIds}")
    @RequiresPermissions("activity:delete")
    @ControllerEndpoint(operation = "删除活动", exceptionMessage = "删除活动失败")
    public FebsResponse deleteActivity(@NotBlank(message = "{required}") @PathVariable String tActivityIds) {
        String[] ids = tActivityIds.split(StringPool.COMMA);
        //获取所有活动id列表
        List<String> list = Arrays.asList(ids);
        //先删除分享
        QueryWrapper<Share> wrapper = null;
        for (String s : list) {
             wrapper = new QueryWrapper<>();
             wrapper.eq("activity_id",s);
            shareService.remove(wrapper);
        }
        //删除活动
        activityService.removeByIds(list);
        return new FebsResponse().success();
    }


}
